import { User } from "@/entities/User";
import { initORM } from "@/utils";
import {
  createMd5,
  sendEmail,
  getRandPassword,
  capitalize,
} from "@/utils/back";
import { NextApiRequest, NextApiResponse } from "next";

async function sendResetEmail(
  req: NextApiRequest,
  res: NextApiResponse<APIRes>
) {
  const tempPwd = getRandPassword();
  const passResetToken = createMd5(tempPwd);
  const email = req.body?.email;
  const domain = process.env.DOMAIN ?? "";
  const resetUrl = `${domain}/user/password/reset?resetKey=${passResetToken}`;
  const userName = email.replace(/@.*/, "").replace(/\..*$/, "");
  const displayName = capitalize(userName);
  const ok = await sendEmail(
    email,
    "[Airoxy config center] Reset Password",
    `Hello, ${displayName}: <p>You can reset passsword by click this link: <a target="_blank" href="${resetUrl}">${resetUrl}</a></p>`
  );
  if (!ok) {
    res
      .status(400)
      .json({ success: false, data: {}, message: "Email send failed" });
    return;
  }

  const em = await initORM();
  const user = await em.findOne<InstanceType<typeof User>>(User, { email });
  if (!user) {
    res
      .status(400)
      .json({ success: false, data: {}, message: "User not found" });
    return;
  }

  user.passResetToken = passResetToken;

  await em.persistAndFlush(user);

  res.status(200).json({
    success: true,
    data: user ?? {},
    message: `Please check your email: ${email} `,
  });
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<APIRes>
) {
  if (req.method === "POST") {
    sendResetEmail(req, res);
  } else {
    res
      .status(405)
      .json({ success: false, data: {}, message: "Method not allowed" });
  }
}
